package com.hanlin.leetcode;

import java.util.*;

/**
 * 栈实现队列
 * https://leetcode.cn/problems/implement-queue-using-stacks/description/
 */
public class StackToQueue {

    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.push(1);
        myQueue.push(2);
        System.out.println(myQueue.pop());
        myQueue.push(3);
        System.out.println(myQueue.pop());
        System.out.println(myQueue.pop());
    }

}

class MyQueue {

    private Stack<Integer> stack;
    private Stack<Integer> helper;

    public MyQueue() {
        stack = new Stack<>();
        helper = new Stack<>();
    }

    /**
     * 将元素 x 推到队列的末尾
     *
     * @param x
     */
    public void push(int x) {
        stack.push(x);
    }

    /**
     * 从队列的开头移除并返回元素
     *
     * @return
     */
    public int pop() {
        if (helper.empty()) {
            exchangeData();
        }
        if (helper.empty()) {
            throw new RuntimeException("栈里没有数据了");
        }
        return helper.pop();
    }

    /**
     * 返回队列开头的元素
     *
     * @return
     */
    public int peek() {
        if (helper.empty()) {
            exchangeData();
        }
        if (helper.empty()) {
            throw new RuntimeException("栈里没有数据了");
        }
        return helper.peek();
    }

    /**
     * 交换数据
     */
    public void exchangeData() {
        while (!stack.empty()) {
            helper.push(stack.pop());
        }
    }

    /**
     * 如果队列为空，返回 true ；否则，返回 false
     *
     * @return
     */
    public boolean empty() {
        boolean isStack = stack != null && !stack.empty();
        boolean isHelper = helper != null && !helper.empty();
        return !isStack && !isHelper;
    }
}

/**
 * https://leetcode.cn/problems/first-unique-character-in-a-string/description/
 * 给定一个字符串 s ，找到 它的第一个不重复的字符，并返回它的索引 。如果不存在，则返回 -1 。
 */
class Solution_387 {
    public int firstUniqChar(String s) {
        if (s == null || s.length() == 0) {
            return -1;
        }
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char str = s.charAt(i);
            map.put(str, map.getOrDefault(str, 0) + 1);
        }
        for (int i = 0; i < s.length(); i++) {
            if (map.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }
}
